package MainDistrib;

import java.io.IOException;
import java.util.ArrayList;

import worker.ManagerImpl;
import worker.Worker;

import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.core.body.migration.MigrationException;
import org.objectweb.proactive.core.node.NodeException;

import Client.Client;
import Task.DataCheckInFile;
import Task.MapCompteMots;
import Task.ReduceCompteMots;
import Task.SplitCompteMots;
import Task.Task;

public class ClientDistrib {

	
	
	
	public static void main (String[] args) throws ActiveObjectCreationException, NodeException, MigrationException {
		
		try {
			ManagerImpl ref = PAActiveObject.lookupActive(ManagerImpl.class, "//jerome-laptop:1099/entryPoint");
			ManagerImpl manager = PAActiveObject.newActive(ManagerImpl.class, null);
			manager.connectTo(ref);
			
			//D�claration des variables.
			Task tache = PAActiveObject.newActive( Task.class , null );
			Client client = PAActiveObject.newActive( Client.class , null );
			
			// Initialisation des variables.
			tache.setSplit( PAActiveObject.newActive( SplitCompteMots.class ,null) );
			tache.setMap( PAActiveObject.newActive( MapCompteMots.class , null ) );
			tache.setReduce( PAActiveObject.newActive( ReduceCompteMots.class , null ) );
			tache.setData( PAActiveObject.newActive( DataCheckInFile.class , null ) );
			client.setTache(tache);
			
			// GetWorker() depuis le Master.
			ArrayList<Worker> workers = manager.getMaster().getWorkers();
			
			System.out.println("workers connect�s : " + workers.size() );
			
			//Initialisation de Data.
			client.getTache().getData().setData( client.readFromFile("./Data/test1.txt") );
			System.out.println("data : " + client.getTache().getData().getData() );
			
			// SPLIT()
			//							split(  					Data		, 		NbWorkers			).
			client.getTache().getSplit().split( client.getTache().getData().getData() , workers.size() );
			
			// pushData() + submit() + map()
			
			for(int i = 0; i < workers.size() ; ++i) {
				
				workers.get(i).pushData( client.getTache().getSplit().getResult().get(i) );
			}
			
			for(int i = 0; i < workers.size() ; ++i) {
				
				workers.get(i).submit( new MapCompteMots(),  new ReduceCompteMots() , workers , i );
			}
			
			//Recup�ration des r�sultats : 
			for(int i = 0; i < workers.size() ; ++i) {
				
				client.addToResult( workers.get(i).getReduce().getHashtable() );
			}
			System.out.println("Resultat : " + client.getResult() );
			
			
		} catch (IOException e) {
			System.out.println("Aucun workers de connect�s");
			e.printStackTrace();
		}
	}
}
